package com.shuda.business.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.crm.entity.CustomerEntity;
import com.shuda.business.crm.entity.FollowUpRecordEntity;
import com.shuda.business.crm.entity.AllocationRecordEntity;
import com.shuda.business.crm.mapper.CustomerMapper;
import com.shuda.business.crm.mapper.FollowUpRecordMapper;
import com.shuda.business.crm.mapper.AllocationRecordMapper;
import com.shuda.business.crm.service.CrmService;
import com.shuda.common.dto.CustomerDTO;
import com.shuda.common.dto.FollowUpRecordDTO;
import com.shuda.common.dto.AllocationRecordDTO;
import com.shuda.common.security.SecurityUtils;
// 移除Lombok依赖，改为显式构造注入
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * CRM服务实现类
 */
@Service
public class CrmServiceImpl extends ServiceImpl<CustomerMapper, CustomerEntity> implements CrmService {

    private final CustomerMapper customerMapper;
    private final FollowUpRecordMapper followUpRecordMapper;
    private final AllocationRecordMapper allocationRecordMapper;

    /**
     *
     * CrmServiceImpl 构造方法
     * @param customerMapper 客户Mapper
     * @param followUpRecordMapper 跟进记录Mapper
     * @param allocationRecordMapper 分配记录Mapper
     * @return $returns$
     * @author ink
     * @Description: 显式构造器注入，移除对Lombok的依赖
     * @date 2025-11-10 00:05
     */
    public CrmServiceImpl(CustomerMapper customerMapper,
                          FollowUpRecordMapper followUpRecordMapper,
                          AllocationRecordMapper allocationRecordMapper) {
        this.customerMapper = customerMapper;
        this.followUpRecordMapper = followUpRecordMapper;
        this.allocationRecordMapper = allocationRecordMapper;
    }

    /**
     * 客户管理相关方法
     */
    @Override
    public IPage<CustomerEntity> getCustomerList(Integer pageNum, Integer pageSize, String customerName, String phone, String status, Long channelId, Long assignedUserId) {
        Page<CustomerEntity> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<CustomerEntity> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.eq(CustomerEntity::getDeleted, false);
        
        if (customerName != null && !customerName.trim().isEmpty()) {
            wrapper.like(CustomerEntity::getCustomerName, customerName);
        }
        if (phone != null && !phone.trim().isEmpty()) {
            wrapper.like(CustomerEntity::getPhone, phone);
        }
        if (status != null && !status.trim().isEmpty()) {
            wrapper.eq(CustomerEntity::getStatus, status);
        }
        if (channelId != null) {
            wrapper.eq(CustomerEntity::getChannelId, channelId);
        }
        if (assignedUserId != null) {
            wrapper.eq(CustomerEntity::getAssignedUserId, assignedUserId);
        }
        
        wrapper.orderByDesc(CustomerEntity::getCreateTime);
        return customerMapper.selectPage(page, wrapper);
    }

    @Override
    public CustomerEntity getCustomerById(Long id) {
        return customerMapper.selectById(id);
    }

    @Override
    @Transactional
    public Boolean createCustomer(CustomerDTO customerDTO) {
        CustomerEntity customer = new CustomerEntity();
        customer.setCustomerName(customerDTO.getCustomerName());
        customer.setPhone(customerDTO.getPhone());
        customer.setIdCard(customerDTO.getIdCard());
        customer.setAge(customerDTO.getAge());
        customer.setGender(customerDTO.getGender());
        customer.setEducation(customerDTO.getEducation());
        customer.setOccupation(customerDTO.getOccupation());
        customer.setMonthlyIncome(customerDTO.getMonthlyIncome());
        customer.setCity(customerDTO.getCity());
        customer.setAddress(customerDTO.getAddress());
        customer.setWechat(customerDTO.getWechat());
        customer.setQq(customerDTO.getQq());
        customer.setEmail(customerDTO.getEmail());
        customer.setSource(customerDTO.getSource());
        customer.setChannelId(customerDTO.getChannelId());
        customer.setChannelName(customerDTO.getChannelName());
        customer.setProductType(customerDTO.getProductType());
        customer.setLoanAmount(customerDTO.getLoanAmount());
        customer.setLoanTerm(customerDTO.getLoanTerm());
        customer.setStatus("active");
        customer.setFollowUpStatus("pending");
        customer.setAllocationStatus("unassigned");
        customer.setFollowUpCount(0);
        customer.setIsValid(true);
        customer.setRemark(customerDTO.getRemark());
        customer.setExt1(customerDTO.getExt1());
        customer.setExt2(customerDTO.getExt2());
        customer.setExt3(customerDTO.getExt3());
        customer.setTenantId(SecurityUtils.getCurrentTenantId());
        
        return customerMapper.insert(customer) > 0;
    }

    @Override
    @Transactional
    public Boolean updateCustomer(Long id, CustomerDTO customerDTO) {
        CustomerEntity customer = customerMapper.selectById(id);
        if (customer == null) {
            return false;
        }
        
        customer.setCustomerName(customerDTO.getCustomerName());
        customer.setPhone(customerDTO.getPhone());
        customer.setIdCard(customerDTO.getIdCard());
        customer.setAge(customerDTO.getAge());
        customer.setGender(customerDTO.getGender());
        customer.setEducation(customerDTO.getEducation());
        customer.setOccupation(customerDTO.getOccupation());
        customer.setMonthlyIncome(customerDTO.getMonthlyIncome());
        customer.setCity(customerDTO.getCity());
        customer.setAddress(customerDTO.getAddress());
        customer.setWechat(customerDTO.getWechat());
        customer.setQq(customerDTO.getQq());
        customer.setEmail(customerDTO.getEmail());
        customer.setSource(customerDTO.getSource());
        customer.setChannelId(customerDTO.getChannelId());
        customer.setChannelName(customerDTO.getChannelName());
        customer.setProductType(customerDTO.getProductType());
        customer.setLoanAmount(customerDTO.getLoanAmount());
        customer.setLoanTerm(customerDTO.getLoanTerm());
        customer.setRemark(customerDTO.getRemark());
        customer.setExt1(customerDTO.getExt1());
        customer.setExt2(customerDTO.getExt2());
        customer.setExt3(customerDTO.getExt3());
        
        return customerMapper.updateById(customer) > 0;
    }

    @Override
    @Transactional
    public Boolean deleteCustomer(Long id) {
        return customerMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional
    public Boolean updateCustomerStatus(Long id, String status) {
        CustomerEntity customer = customerMapper.selectById(id);
        if (customer == null) {
            return false;
        }
        customer.setStatus(status);
        return customerMapper.updateById(customer) > 0;
    }

    @Override
    @Transactional
    public Boolean addFollowUpRecord(Long customerId, FollowUpRecordDTO followUpDTO) {
        CustomerEntity customer = customerMapper.selectById(customerId);
        if (customer == null) {
            return false;
        }
        
        FollowUpRecordEntity record = new FollowUpRecordEntity();
        record.setCustomerId(customerId);
        record.setCustomerName(customer.getCustomerName());
        record.setCustomerPhone(customer.getPhone());
        record.setFollowUpMethod(followUpDTO.getFollowUpMethod());
        record.setFollowUpContent(followUpDTO.getFollowUpContent());
        record.setFollowUpResult(followUpDTO.getFollowUpResult());
        record.setCustomerIntention(followUpDTO.getCustomerIntention());
        record.setNextFollowUpTime(followUpDTO.getNextFollowUpTime());
        record.setFollowUpUserId(SecurityUtils.getCurrentUserId());
        record.setFollowUpUserName(SecurityUtils.getCurrentUsername());
        record.setFollowUpTime(LocalDateTime.now());
        record.setCallDuration(followUpDTO.getCallDuration());
        record.setRecordingFile(followUpDTO.getRecordingFile());
        record.setIsAppointment(followUpDTO.getIsAppointment());
        record.setAppointmentTime(followUpDTO.getAppointmentTime());
        record.setIsDeal(followUpDTO.getIsDeal());
        record.setDealAmount(followUpDTO.getDealAmount());
        record.setRemark(followUpDTO.getRemark());
        record.setTenantId(SecurityUtils.getCurrentTenantId());
        
        // 更新客户信息
        customer.setLastFollowUpTime(LocalDateTime.now());
        customer.setNextFollowUpTime(followUpDTO.getNextFollowUpTime());
        customer.setFollowUpCount(customer.getFollowUpCount() + 1);
        customer.setFollowUpStatus("followed");
        
        customerMapper.updateById(customer);
        return followUpRecordMapper.insert(record) > 0;
    }

    @Override
    @Transactional
    public Boolean assignCustomer(Long customerId, Long userId) {
        CustomerEntity customer = customerMapper.selectById(customerId);
        if (customer == null) {
            return false;
        }
        
        customer.setAssignedUserId(userId);
        customer.setAssignedTime(LocalDateTime.now());
        customer.setAllocationStatus("assigned");
        
        return customerMapper.updateById(customer) > 0;
    }

    @Override
    @Transactional
    public Boolean transferCustomer(Long customerId, Long targetUserId) {
        CustomerEntity customer = customerMapper.selectById(customerId);
        if (customer == null) {
            return false;
        }
        
        customer.setAssignedUserId(targetUserId);
        customer.setAssignedTime(LocalDateTime.now());
        
        return customerMapper.updateById(customer) > 0;
    }

    @Override
    @Transactional
    public Boolean markCustomerInvalid(Long customerId, String invalidReason) {
        CustomerEntity customer = customerMapper.selectById(customerId);
        if (customer == null) {
            return false;
        }
        
        customer.setIsValid(false);
        customer.setInvalidReason(invalidReason);
        customer.setStatus("invalid");
        
        return customerMapper.updateById(customer) > 0;
    }

    @Override
    public String exportCustomers(String query) {
        // 实现导出逻辑，返回文件下载地址
        return "/api/file/download/customers_export_" + System.currentTimeMillis() + ".xlsx";
    }

    /**
     * 跟进记录相关方法
     */
    @Override
    public IPage<FollowUpRecordEntity> getFollowUpList(Integer pageNum, Integer pageSize, Long customerId, String followUpMethod, LocalDateTime startTime, LocalDateTime endTime) {
        Page<FollowUpRecordEntity> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<FollowUpRecordEntity> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.eq(FollowUpRecordEntity::getDeleted, false);
        
        if (customerId != null) {
            wrapper.eq(FollowUpRecordEntity::getCustomerId, customerId);
        }
        if (followUpMethod != null && !followUpMethod.trim().isEmpty()) {
            wrapper.eq(FollowUpRecordEntity::getFollowUpMethod, followUpMethod);
        }
        if (startTime != null) {
            wrapper.ge(FollowUpRecordEntity::getFollowUpTime, startTime);
        }
        if (endTime != null) {
            wrapper.le(FollowUpRecordEntity::getFollowUpTime, endTime);
        }
        
        wrapper.orderByDesc(FollowUpRecordEntity::getFollowUpTime);
        return followUpRecordMapper.selectPage(page, wrapper);
    }

    @Override
    public FollowUpRecordEntity getFollowUpById(Long id) {
        return followUpRecordMapper.selectById(id);
    }

    @Override
    @Transactional
    public Boolean createFollowUp(FollowUpRecordDTO followUpDTO) {
        FollowUpRecordEntity record = new FollowUpRecordEntity();
        record.setCustomerId(followUpDTO.getCustomerId());
        record.setCustomerName(followUpDTO.getCustomerName());
        record.setCustomerPhone(followUpDTO.getCustomerPhone());
        record.setFollowUpMethod(followUpDTO.getFollowUpMethod());
        record.setFollowUpContent(followUpDTO.getFollowUpContent());
        record.setFollowUpResult(followUpDTO.getFollowUpResult());
        record.setCustomerIntention(followUpDTO.getCustomerIntention());
        record.setNextFollowUpTime(followUpDTO.getNextFollowUpTime());
        record.setFollowUpUserId(SecurityUtils.getCurrentUserId());
        record.setFollowUpUserName(SecurityUtils.getCurrentUsername());
        record.setFollowUpTime(LocalDateTime.now());
        record.setCallDuration(followUpDTO.getCallDuration());
        record.setRecordingFile(followUpDTO.getRecordingFile());
        record.setIsAppointment(followUpDTO.getIsAppointment());
        record.setAppointmentTime(followUpDTO.getAppointmentTime());
        record.setIsDeal(followUpDTO.getIsDeal());
        record.setDealAmount(followUpDTO.getDealAmount());
        record.setRemark(followUpDTO.getRemark());
        record.setTenantId(SecurityUtils.getCurrentTenantId());
        
        return followUpRecordMapper.insert(record) > 0;
    }

    @Override
    @Transactional
    public Boolean updateFollowUp(Long id, FollowUpRecordDTO followUpDTO) {
        FollowUpRecordEntity record = followUpRecordMapper.selectById(id);
        if (record == null) {
            return false;
        }
        
        record.setFollowUpMethod(followUpDTO.getFollowUpMethod());
        record.setFollowUpContent(followUpDTO.getFollowUpContent());
        record.setFollowUpResult(followUpDTO.getFollowUpResult());
        record.setCustomerIntention(followUpDTO.getCustomerIntention());
        record.setNextFollowUpTime(followUpDTO.getNextFollowUpTime());
        record.setCallDuration(followUpDTO.getCallDuration());
        record.setRecordingFile(followUpDTO.getRecordingFile());
        record.setIsAppointment(followUpDTO.getIsAppointment());
        record.setAppointmentTime(followUpDTO.getAppointmentTime());
        record.setIsDeal(followUpDTO.getIsDeal());
        record.setDealAmount(followUpDTO.getDealAmount());
        record.setRemark(followUpDTO.getRemark());
        
        return followUpRecordMapper.updateById(record) > 0;
    }

    @Override
    @Transactional
    public Boolean deleteFollowUp(Long id) {
        return followUpRecordMapper.deleteById(id) > 0;
    }

    /**
     * 分配记录相关方法
     */
    @Override
    public IPage<AllocationRecordEntity> getAllocationList(Integer pageNum, Integer pageSize, Long customerId, Long assignedUserId, String status, LocalDateTime startTime, LocalDateTime endTime) {
        Page<AllocationRecordEntity> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<AllocationRecordEntity> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.eq(AllocationRecordEntity::getDeleted, false);
        
        if (customerId != null) {
            wrapper.eq(AllocationRecordEntity::getCustomerId, customerId);
        }
        if (assignedUserId != null) {
            wrapper.eq(AllocationRecordEntity::getTargetUserId, assignedUserId);
        }
        if (status != null && !status.trim().isEmpty()) {
            wrapper.eq(AllocationRecordEntity::getStatus, status);
        }
        if (startTime != null) {
            wrapper.ge(AllocationRecordEntity::getAllocationTime, startTime);
        }
        if (endTime != null) {
            wrapper.le(AllocationRecordEntity::getAllocationTime, endTime);
        }
        
        wrapper.orderByDesc(AllocationRecordEntity::getAllocationTime);
        return allocationRecordMapper.selectPage(page, wrapper);
    }

    @Override
    public AllocationRecordEntity getAllocationById(Long id) {
        return allocationRecordMapper.selectById(id);
    }

    @Override
    @Transactional
    public Boolean manualAllocation(AllocationRecordDTO allocationDTO) {
        AllocationRecordEntity record = new AllocationRecordEntity();
        record.setCustomerId(allocationDTO.getCustomerId());
        record.setCustomerName(allocationDTO.getCustomerName());
        record.setCustomerPhone(allocationDTO.getCustomerPhone());
        record.setOriginalUserId(allocationDTO.getOriginalUserId());
        record.setOriginalUserName(allocationDTO.getOriginalUserName());
        record.setTargetUserId(allocationDTO.getTargetUserId());
        record.setTargetUserName(allocationDTO.getTargetUserName());
        record.setAllocationType("manual");
        record.setAllocationReason(allocationDTO.getAllocationReason());
        record.setStatus("pending");
        record.setAllocatedBy(SecurityUtils.getCurrentUserId());
        record.setAllocatedByName(SecurityUtils.getCurrentUsername());
        record.setAllocationTime(LocalDateTime.now());
        record.setRemark(allocationDTO.getRemark());
        record.setTenantId(SecurityUtils.getCurrentTenantId());
        
        // 更新客户分配信息
        CustomerEntity customer = customerMapper.selectById(allocationDTO.getCustomerId());
        if (customer != null) {
            customer.setAssignedUserId(allocationDTO.getTargetUserId());
            customer.setAssignedTime(LocalDateTime.now());
            customer.setAllocationStatus("assigned");
            customerMapper.updateById(customer);
        }
        
        return allocationRecordMapper.insert(record) > 0;
    }

    @Override
    @Transactional
    public Boolean processAllocation(Long id, String processRemark) {
        AllocationRecordEntity record = allocationRecordMapper.selectById(id);
        if (record == null) {
            return false;
        }
        
        record.setStatus("processed");
        record.setProcessRemark(processRemark);
        record.setProcessTime(LocalDateTime.now());
        
        return allocationRecordMapper.updateById(record) > 0;
    }

    @Override
    @Transactional
    public Boolean deleteAllocation(Long id) {
        return allocationRecordMapper.deleteById(id) > 0;
    }

    @Override
    public String exportAllocations(String query) {
        // 实现导出逻辑，返回文件下载地址
        return "/api/file/download/allocations_export_" + System.currentTimeMillis() + ".xlsx";
    }
}